<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace weapp\PointsShop\model;

use think\Db;
use think\Page;
use think\Model;

/**
 * 积分商品规格模型
 */
load_trait('controller/Jump');

class PointsGoods extends Model
{
    use \traits\controller\Jump;

    // 数据表名
    public $name = 'weapp_points_goods';

    // 初始化
    protected function initialize()
    {
        // 需要调用`Model`的`initialize`方法
        parent::initialize();
        // 当前时间戳
        $this->times = getTime();
        // 积分商品表
        $this->points_goods_db = Db::name('weapp_points_goods');
        // 积分商品表
        $this->points_goods_spec_db = Db::name('weapp_points_goods_spec');
        // 系统订单表
        $this->shop_order_db = Db::name('shop_order');
        $this->order_details_db = Db::name('shop_order_details');
    }

    public function getPointsGoodsList($title = '', $goods_status = 0, $startTime = '', $stopTime = '')
    {
        $where = [
            'a.goods_save' => 1,
        ];
        // 系统商品标题查询
        if (!empty($title)) {
            $aids = Db::name('archives')->where(['channel' => 2, 'title' => ['LIKE', "%{$title}%"]])->column('aid');
            if (!empty($aids)) {
                $where['a.aid'] = ['IN', $aids];
            } else {
                return ['list' => []];
            }
        }
        // 积分商品状态查询
        if (!empty($goods_status)) $where['a.goods_status'] = intval($goods_status);
        // 积分商品添加时间查询
        $startTime = strtotime($startTime);
        !empty($stopTime) && $stopTime .= ' 23:59:59';
        $stopTime = strtotime($stopTime);
        if ($startTime > 0 && $stopTime > 0) {
            $where['a.add_time'] = array('between', "$startTime, $stopTime");
        } else if ($startTime > 0) {
            $where['a.add_time'] = array('egt', $startTime);
        } else if ($stopTime > 0) {
            $where['a.add_time'] = array('elt', $stopTime);
        }
        
        // 分页查询
        $count = $this->points_goods_db->alias('a')->where($where)->count('goods_id');
        $Page = new Page($count, config('paginate.list_rows'));

        // 积分商品查询
        $limit = $Page->firstRow.','.$Page->listRows;
        $field = 'a.*, b.title, b.litpic, b.prom_type';
        $list = $this->points_goods_db->alias('a')->field($field)->join('__ARCHIVES__ b', 'a.aid = b.aid', 'LEFT')->where($where)->limit($limit)->order('add_time desc, goods_id desc')->select();

        // 积分商品规格查询
        $where = [
            'goods_id' => ['IN', get_arr_column($list, 'goods_id')],
        ];
        $goodsSpec = $this->points_goods_spec_db->where($where)->order('spec_points asc')->select();
        $goodsSpec = !empty($goodsSpec) ? group_same_key($goodsSpec, 'goods_id') : [];

        // 查询积分商品订单
        $where = [
            // 'a.order_status' => 3,
            'a.points_shop_order' => 1,
        ];
        $field = 'a.order_id, a.points_shop_order, b.product_id, b.data as product_data';
        $shopOrder = $this->shop_order_db->alias('a')->field($field)->join('__SHOP_ORDER_DETAILS__ b', 'a.order_id = b.order_id', 'LEFT')->where($where)->select();
        $shopOrderCount = [];
        if (!empty($shopOrder)) {
            foreach ($shopOrder as $key => $value) {
                $productData = !empty($value['product_data']) ? unserialize($value['product_data']) : [];
                $pointsGoodsBuyField = !empty($productData['pointsGoodsBuyField']) ? json_decode($productData['pointsGoodsBuyField'], true) : [];
                $value['goodsBuyNumber'] = !empty($pointsGoodsBuyField['goodsBuyNumber']) ? intval($pointsGoodsBuyField['goodsBuyNumber']) : 0;
                $value['goodsSinglePrice'] = !empty($pointsGoodsBuyField['goodsSinglePrice']) ? intval($pointsGoodsBuyField['goodsSinglePrice']) : 0;
                $value['goodsSinglePoints'] = !empty($pointsGoodsBuyField['goodsSinglePoints']) ? intval($pointsGoodsBuyField['goodsSinglePoints']) : 0;
                $shopOrder[$key] = $value;
            }
            $shopOrder = !empty($shopOrder) ? group_same_key($shopOrder, 'product_id') : [];
            foreach ($shopOrder as $key => $value) {
                // 订单销售数量总和
                $goodsBuyNumber = array_column($value, 'goodsBuyNumber');
                $shopOrderCount[$key]['goodsSalesNumber'] = array_sum($goodsBuyNumber);
                // 订单销售额总和(积分)
                $goodsSinglePrice = array_column($value, 'goodsSinglePrice');
                $shopOrderCount[$key]['goodsSalesPrice'] = array_sum($goodsSinglePrice);
                // 订单销售额总和(金额)
                $goodsSinglePoints = array_column($value, 'goodsSinglePoints');
                $shopOrderCount[$key]['goodsSalesPoints'] = array_sum($goodsSinglePoints);
            }
        }

        // 处理积分商品数据
        foreach ($list as $key => $value) {
            $value['arcurl'] = get_arcurl($value);
            $value['litpic'] = handle_subdir_pic($value['litpic']);
            // 积分商品购买价格综合显示处理
            $value['goodsComplexShow'] = $value['goods_points'] . '积分 + ' . $value['goods_price'] . '元';
            if (!empty($value['goods_spec']) && !empty($goodsSpec[$value['goods_id']])) {
                $goodsSpecValue = $goodsSpec[$value['goods_id']];
                $minPrice = min($goodsSpecValue);
                $maxPrice = max($goodsSpecValue);
                $value['goods_price'] = $minPrice['spec_price'];
                $value['goods_points'] = $minPrice['spec_points'];
                $value['goods_stock'] = array_sum(get_arr_column($goodsSpecValue, 'spec_stock'));
                $value['goodsComplexShow'] = $minPrice['spec_points'] . '积分 + ' . $minPrice['spec_price'] . '元 ~ ' . $maxPrice['spec_points'] . '积分 + ' . $maxPrice['spec_price'] . '元';
            }

            $value['goodsSalesNumber'] = !empty($shopOrderCount[$value['aid']]['goodsSalesNumber']) ? intval($shopOrderCount[$value['aid']]['goodsSalesNumber']) : 0;
            $value['goodsSalesPrice'] = !empty($shopOrderCount[$value['aid']]['goodsSalesPrice']) ? floatval($shopOrderCount[$value['aid']]['goodsSalesPrice']) : 0;
            $value['goodsSalesPoints'] = !empty($shopOrderCount[$value['aid']]['goodsSalesPoints']) ? intval($shopOrderCount[$value['aid']]['goodsSalesPoints']) : 0;
            $list[$key] = $value;
        }
        // dump($list);exit;
        $result['list'] = $list;
        $result['pager'] = $Page;
        $result['page'] = $Page->show();
        return $result;
    }

    public function getPointsGoods($goodsCookie = 0, $goodsStr = [])
    {
        // 获取指定积分商品
        $where = [
            'aid' => ['IN', $goodsStr],
        ];
        if (!empty($goodsCookie)) $where['goods_cookie'] = intval($goodsCookie);
        $pointsGoods = $this->points_goods_db->where($where)->getAllWithIndex('aid');
        // empty($pointsGoods) && $this->error('请选择编辑的积分商品');

        // 查询是否设置多规格
        $where = [
            'goods_id' => ['IN', get_arr_column($pointsGoods, 'goods_id')],
        ];
        $goodsSetSpec = $this->points_goods_spec_db->where($where)->getAllWithIndex('goods_id');

        // 积分商品数据处理
        foreach ($pointsGoods as $key => $value) {
            $value['goods_spec_set'] = 0;
            if (!empty($goodsSetSpec[$value['goods_id']])) $value['goods_spec_set'] = 1;
            $pointsGoods[$key] = $value;
        }

        return $pointsGoods;
    }

    public function getPointsGoodsDetails($goods_id = 0)
    {
        // 积分商品查询
        $where = [
            'goods_id' => $goods_id,
        ];
        $pointsGoods = $this->points_goods_db->where($where)->find();
        empty($pointsGoods) && $this->error('请选择编辑的积分商品');

        return $pointsGoods;
    }

    public function savePointsGoods($post = [])
    {
        // 数据判断
        if (empty($post['goods_id']) || empty($post['aidInput'])) $this->error('请选择商品');

        $saveAll = [];
        foreach ($post['goods_id'] as $key => $value) {
            $goodsTitle = !empty($post['goods_title'][$value]) ? $post['goods_title'][$value] : '';
            $goodsSpec = !empty($post['goods_spec'][$value]) ? intval($post['goods_spec'][$value]) : 0;
            $goodsStock = !empty($post['goods_stock'][$value]) ? intval($post['goods_stock'][$value]) : 0;
            $goodsPrice = !empty($post['goods_price'][$value]) ? floatval($post['goods_price'][$value]) : 0;
            $goodsPoints = !empty($post['goods_points'][$value]) ? intval($post['goods_points'][$value]) : 0;
            $goodsSpecSet = !empty($post['goods_spec_set'][$value]) ? intval($post['goods_spec_set'][$value]) : 0;
            if (empty($goodsStock) && empty($goodsSpec)) $this->error('请设置 【' . $goodsTitle . '】 库存量');
            if (empty($goodsPoints) && empty($goodsSpec)) $this->error('请设置 【' . $goodsTitle . '】 积分价');
            if (empty($goodsSpecSet) && !empty($goodsSpec)) $this->error('请设置 【' . $goodsTitle . '】 积分价及库存', null, ['id'=>'#notSet_' . $value]);
            // 积分商品数据
            $saveAll[] = [
                'goods_id' => intval($value),
                'goods_spec' => $goodsSpec,
                'goods_stock' => $goodsStock,
                'goods_price' => $goodsPrice,
                'goods_points' => $goodsPoints,
                'goods_status' => !empty($post['goods_status']) ? intval($post['goods_status']) : 1,
                'goods_shipping' => !empty($post['goods_shipping']) ? intval($post['goods_shipping']) : 1,
                'goods_save' => 1,
                'update_time' => $this->times,
            ];
        }

        // 保存规格数据
        $result = false;
        // 保存数据
        if (!empty($saveAll)) $result = $this->saveAll($saveAll);
        // 返回提示
        if (!empty($result)) {
            $this->success('保存成功');
        } else {
            $this->error('保存失败');
        }
    }

    public function delPointsGoods($goodsCookie = 0, $goods_id = [])
    {
        $result = false;
        // 删除积分商品及规格
        if (!empty($goods_id)) {
            $where = [
                'goods_id' => ['IN', $goods_id]
            ];
        } else {
            $where = [
                'goods_save' => 0,
                'goods_cookie' => intval($goodsCookie),
            ];
        }
        $goodsIds = $this->points_goods_db->where($where)->column('goods_id');
        if (!empty($goodsIds)) {
            $where = [
                'goods_id' => ['IN', $goodsIds],
            ];
            $delete_1 = $this->points_goods_db->where($where)->delete(true);
            $delete_2 = $this->points_goods_spec_db->where($where)->delete(true);
            if (!empty($delete_1)) $result = true;
        }

        if (!empty($goods_id)) return $result;
    }

    public function updatePointsGoods($goods_id = 0, $goods_status = 0)
    {
        $where = [
            'goods_id' => intval($goods_id),
        ];
        $update = [
            'goods_status' => intval($goods_status),
        ];
        $result = false;
        $update = $this->points_goods_db->where($where)->update($update);
        if (!empty($update)) $result = true;

        return $result;
    }
}